package com.tender.shiro.jwt;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import com.tender.jwt.JwtTokenManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

import com.tender.constants.Constants;

public class ShiroSessionManager extends DefaultWebSessionManager {


    private static final String AUTHORIZATION = Constants.AUTHORIZATION_HEADER;

    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

    public ShiroSessionManager() {
        super();
    }

    @Autowired
    private JwtTokenManager jwtTokenManager;

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String jwtToken = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
        if (StringUtils.isBlank(jwtToken)) {
            // 如果没有携带 jwtToken 参数，则按照父类的方式在cookie进行获取
            return super.getSessionId(request, response);
        } else {
            // 如果请求头中有 authToken 则其值为jwtToken，然后解析出会话session
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
            // 解析出 jwt
            Claims decode = jwtTokenManager.decodeToken(jwtToken);
            // 生成sessionId
            String id = (String) decode.get(Constants.SESSION_ID_FROM_JTI);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return id;
        }
    }
}
